package com.xmall.config;

import org.springframework.boot.task.TaskSchedulerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务配置
 */
@Configuration
public class ThreadTaskConfig {

    @Resource
    private ThreadTaskProperties threadTaskProperties;

    /**
     * 异步任务使用
     */
    @Bean("asyncTaskThreadPool")
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadTaskProperties.getAsyncCore());
        executor.setMaxPoolSize(threadTaskProperties.getAsyncMax());
        executor.setQueueCapacity(threadTaskProperties.getAsyncQueueSize());
        executor.setKeepAliveSeconds(threadTaskProperties.getAsyncKeepAliveSeconds());
        executor.setThreadNamePrefix("AsyncTaskThreadPool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setAllowCoreThreadTimeOut(true);
        executor.initialize();
        return executor;
    }

    /**
     * 定时任务使用
     */
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new TaskSchedulerBuilder()
                .poolSize(threadTaskProperties.getTimerCore())
                .threadNamePrefix("TimerTaskThreadPool-")
                .build();
        taskScheduler.setRemoveOnCancelPolicy(true);//是否将取消后的任务从队列删除
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.initialize();
        return taskScheduler;
    }
}
